package com.example.service.serviceImpl;

import com.example.entity.config.AppConfig;
import com.example.entity.constants.Constants;
import com.example.entity.dto.TokenUserInfoDTO;
import com.example.entity.po.UserInfo;
import com.example.entity.po.UserInfoBeauty;
import com.example.entity.query.UserInfoBeautyQuery;
import com.example.entity.vo.PaginationResultVO;
import com.example.entity.vo.UserInfoVO;
import com.example.enums.*;
import com.example.entity.query.SimplePage;
import com.example.entity.query.UserInfoQuery;
import com.example.exception.BusinessException;
import com.example.mapper.UserInfoBeautyMapper;
import com.example.redis.RedisComponent;
import com.example.service.UserInfoService;
import com.example.mapper.UserInfoMapper;
import com.example.utils.CopyTools;
import com.example.utils.StringTools;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Struct;
import java.util.*;

/**
 * @Description:用户信息表 业务接口
 * 
 * @Date:2024/07/12
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {

	@Resource
	private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;
	@Resource
	private UserInfoBeautyMapper<UserInfoBeauty, UserInfoBeautyQuery> userInfoBeautyMapper;
	@Resource
	private AppConfig appConfig;
	@Resource
	private RedisComponent redisComponent;

	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<UserInfo> findListByParam(UserInfoQuery query) {
		return this.userInfoMapper.selectList(query);
	}

	/**
	 * 根据条件查询数量
	 */
	@Override
	public Integer findCountByParam(UserInfoQuery query) {
		return this.userInfoMapper.selectCount(query);
	}

	/**
	 * 分页查询
	 */
	@Override
	public PaginationResultVO<UserInfo> findListByPage(UserInfoQuery query) {
		Integer count = this.findCountByParam(query);
		Integer pageSize = query.getPageSize() == null ? PageSize.SIZE15.getSize() : query.getPageSize();
		SimplePage page = new SimplePage(query.getPageNo(), count, pageSize);
		query.setSimplePage(page);
		List<UserInfo> list = this.findListByParam(query);
		PaginationResultVO<UserInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */

	@Override
	public Integer add(UserInfo bean) {
		return this.userInfoMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<UserInfo> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userInfoMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增/修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<UserInfo> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userInfoMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 根据UserId查询
	 */
	@Override
	public UserInfo getUserInfoByUserId (String userId) {
		return this.userInfoMapper.selectByUserId(userId);
	}

	/**
	 * 根据UserId修改
	 */
	@Override
	public Integer updateUserInfoByUserId(UserInfo bean, String userId) {
		return this.userInfoMapper.updateByUserId(bean, userId);
	}

	/**
	 * 根据UserId删除
	 */
	@Override
	public Integer deleteUserInfoByUserId(String userId) {
		return this.userInfoMapper.deleteByUserId(userId);
	}


	/**
	 * 根据Email查询
	 */
	@Override
	public UserInfo getUserInfoByEmail (String email) {
		return this.userInfoMapper.selectByEmail(email);
	}

	/**
	 * 根据Email修改
	 */
	@Override
	public Integer updateUserInfoByEmail(UserInfo bean, String email) {
		return this.userInfoMapper.updateByEmail(bean, email);
	}



	/**
	 * 根据Email删除
	 */
	@Override
	public Integer deleteUserInfoByEmail(String email) {
		return this.userInfoMapper.deleteByEmail(email);
	}

	/**
	 * 注册
	 * @param email
	 * @param password
	 * @param nickName
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void register(String email, String nickName, String password) {

		Map<String, Object> result = new HashMap<>();
		UserInfo userInfo = this.userInfoMapper.selectByEmail(email);

		if (null != userInfo) {
			try {
				throw new BusinessException("邮箱账号已存在");
			} catch (BusinessException e) {
				throw new RuntimeException(e);
			}
		}
		String userId = StringTools.getUserId();

		UserInfoBeauty beautyAccount = userInfoBeautyMapper.selectByEmail(email);
		Boolean useBeautyAccount =  null != beautyAccount && BeautyAccountStatusEnum
				.NO_USE.getStatus().equals(beautyAccount.getStatus());
		 if (useBeautyAccount) {

			 userId = UserContactTypeEnum.USER.getPrefix() +beautyAccount.getUserId();
		 }
		 Date curDate = new Date();
		 userInfo = new UserInfo();
		 userInfo.setUserId(userId);
		 userInfo.setNickName(nickName);
		 userInfo.setEmail(email);
		 userInfo.setPassword(StringTools.encodeMd5(password));
		 userInfo.setCreateTime(curDate);
		 userInfo.setStatus(UserStatusEnum.ENABLE.getStatus());
		 userInfo.setLastOffTime(curDate.getTime());
		 userInfo.setJoinType(JoinTypeEnum.APPLY.getType());
		 this.userInfoMapper.insert(userInfo);
		 if (useBeautyAccount) {
			 UserInfoBeauty updateBeauty = new UserInfoBeauty();
			 updateBeauty.setStatus(BeautyAccountStatusEnum.USED.getStatus());
			 userInfoBeautyMapper.updateById(updateBeauty,beautyAccount.getId());
		 }
		 //todo 创建机器人好友
	}

	/**
	 * 登录
	 * @param email
	 * @param password
	 */
	@Override
	public UserInfoVO login(String email, String password) {
		UserInfo userInfo = userInfoMapper.selectByEmail(email);
		try {
			if (null == userInfo) {
				throw new BusinessException("账号或者密码不存在");
			}
			if (UserStatusEnum.DISABLE.equals(userInfo.getStatus())) {
				throw new BusinessException("账号已禁用");

			}
		} catch (BusinessException e) {
            throw new RuntimeException(e);
        }
		//todo 查询我的群组
		//todo 查询我的联系人

		TokenUserInfoDTO tokenUserInfoDTO = getTokenUserInfoDTO(userInfo);


		Long lastHeartBeat = redisComponent.getUserHeartBeat(userInfo.getUserId());
		if (lastHeartBeat != null) {
			try {
				throw new BusinessException("此账号已在别处登录，请退出后登录！");
			} catch (BusinessException e) {
				throw new RuntimeException(e);
			}
		}
		//保存登录信息到redis
		String token = StringTools.encodeMd5(tokenUserInfoDTO.getUserId() + StringTools.getRandomString(Constants.LENGTH_20));
		tokenUserInfoDTO.setToken(token);
		redisComponent.saveTokenUserInfoDto(tokenUserInfoDTO);


		UserInfoVO userInfoVO = CopyTools.copy(userInfo, UserInfoVO.class);
		userInfoVO.setToken(tokenUserInfoDTO.getToken());
		userInfoVO.setAdmin(tokenUserInfoDTO.getAdmin());

		return userInfoVO;
	}
	private TokenUserInfoDTO getTokenUserInfoDTO(UserInfo userInfo) {
		TokenUserInfoDTO tokenUserInfoDTO = new TokenUserInfoDTO();
		tokenUserInfoDTO.setUserId(userInfo.getUserId());
		tokenUserInfoDTO.setNickName(userInfo.getNickName());

		String adminEmails = appConfig.getAdminEmails();
		if (!StringUtils.isEmpty(adminEmails) && ArrayUtils.contains(adminEmails.split(","),userInfo.getEmail())) {
			tokenUserInfoDTO.setAdmin(true);
		} else {
			tokenUserInfoDTO.setAdmin(false);
		}
		return tokenUserInfoDTO;
	}
}